<template>
  <div class="container">
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="page-title">用户管理</h1>
        <p class="text-gray-500">管理系统用户账号和权限</p>
      </div>
      <el-button type="primary" @click="openUserDialog(null)">
        <el-icon class="mr-1"><Plus /></el-icon>添加用户
      </el-button>
    </div>
    
    <el-card shadow="hover" class="mb-6">
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="请输入用户名、姓名或部门"
          prefix-icon="Search"
          clearable
          @clear="loadUserData"
          @input="debounceSearch"
          style="width: 240px"
        />
        <el-select 
          v-model="roleFilter" 
          placeholder="角色" 
          clearable 
          @change="loadUserData"
          style="width: 160px"
        >
          <el-option label="全部" value="" />
          <el-option label="管理员" value="admin" />
          <el-option label="普通用户" value="user" />
          <el-option label="驾驶员" value="driver" />
        </el-select>
        <el-button type="primary" @click="loadUserData" :loading="loading">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="overflow-hidden">
      <el-table 
        :data="userList" 
        border 
        stripe 
        style="width: 100%"
        v-loading="loading"
        :header-cell-class-name="'bg-gray-100 dark:bg-gray-700'"
      >
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)" effect="light" class="status-tag">
              {{ getRoleName(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" width="150" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />
        <el-table-column prop="lastLoginTime" label="最近登录时间" width="180" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="changeUserStatus(scope.row)"
              :disabled="scope.row.username === 'admin'"
              class="mx-auto"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="flex gap-2">
              <el-button 
                type="primary" 
                size="small"
                @click="openUserDialog(scope.row)"
                :disabled="scope.row.username === 'admin' && currentUsername !== 'admin'"
              >编辑</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="confirmDeleteUser(scope.row)"
                :disabled="scope.row.username === 'admin'"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>
    
    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        label-position="right"
        class="form-container"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" style="width: 100%" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="驾驶员" value="driver" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input v-model="userForm.confirmPassword" type="password" show-password placeholder="请确认密码" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="userForm.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm" :loading="submitLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'UsersView',
  components: {
    Plus
  },
  setup() {
    // 用户列表数据
    const userList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const searchQuery = ref('')
    const roleFilter = ref('')
    const loading = ref(false)
    const submitLoading = ref(false)
    
    // 当前登录用户
    const currentUsername = ref('admin') // 实际项目中应该从存储中获取
    
    // 用户表单对话框
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const userFormRef = ref(null)
    
    // 用户表单
    const userForm = reactive({
      id: null,
      username: '',
      name: '',
      role: 'user',
      password: '',
      confirmPassword: '',
      department: '',
      phone: '',
      email: '',
      status: 1
    })
    
    // 表单验证规则
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== userForm.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    }
    
    // 初始化
    onMounted(() => {
      loadUserData()
    })
    
    // 防抖搜索
    let searchTimeout = null
    const debounceSearch = () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
      searchTimeout = setTimeout(() => {
        loadUserData()
      }, 500)
    }
    
    // 重置查询条件
    const resetQuery = () => {
      searchQuery.value = ''
      roleFilter.value = ''
      loadUserData()
    }
    
    // 加载用户数据
    const loadUserData = async () => {
      loading.value = true
      try {
        // 实际项目中应从API获取
        /*
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          query: searchQuery.value,
          role: roleFilter.value
        }
        const response = await axios.get('/api/users', { params })
        userList.value = response.data.list
        total.value = response.data.total
        */
        
        // 模拟数据延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 模拟数据
        const mockUsers = [
          {
            id: 1,
            username: 'admin',
            name: '管理员',
            role: 'admin',
            department: '管理部',
            phone: '13800138000',
            email: 'admin@example.com',
            lastLoginTime: '2023-06-18 09:30:45',
            status: 1
          },
          {
            id: 2,
            username: 'zhangsan',
            name: '张三',
            role: 'user',
            department: '行政部',
            phone: '13800138001',
            email: 'zhangsan@example.com',
            lastLoginTime: '2023-06-17 14:20:30',
            status: 1
          },
          {
            id: 3,
            username: 'lisi',
            name: '李四',
            role: 'driver',
            department: '后勤部',
            phone: '13800138002',
            email: 'lisi@example.com',
            lastLoginTime: '2023-06-16 08:45:12',
            status: 1
          },
          {
            id: 4,
            username: 'wangwu',
            name: '王五',
            role: 'user',
            department: '财务部',
            phone: '13800138003',
            email: 'wangwu@example.com',
            lastLoginTime: '2023-06-15 16:35:22',
            status: 0
          }
        ]
        
        // 应用搜索和筛选
        let filteredUsers = [...mockUsers]
        
        if (searchQuery.value) {
          const query = searchQuery.value.toLowerCase()
          filteredUsers = filteredUsers.filter(user => 
            user.username.toLowerCase().includes(query) || 
            user.name.toLowerCase().includes(query) || 
            user.department.toLowerCase().includes(query)
          )
        }
        
        if (roleFilter.value) {
          filteredUsers = filteredUsers.filter(user => user.role === roleFilter.value)
        }
        
        userList.value = filteredUsers
        total.value = filteredUsers.length
      } catch (error) {
        ElMessage.error('获取用户列表失败')
        console.error('获取用户列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 打开用户表单对话框
    const openUserDialog = (user) => {
      if (user) {
        // 编辑用户
        isEdit.value = true
        Object.assign(userForm, user)
      } else {
        // 新增用户
        isEdit.value = false
        Object.keys(userForm).forEach(key => {
          if (key === 'role') {
            userForm[key] = 'user'
          } else if (key === 'status') {
            userForm[key] = 1
          } else {
            userForm[key] = ''
          }
        })
      }
      dialogVisible.value = true
      // 等待DOM更新后重置表单验证
      setTimeout(() => {
        userFormRef.value && userFormRef.value.clearValidate()
      }, 0)
    }
    
    // 提交用户表单
    const submitUserForm = async () => {
      if (!userFormRef.value) return
      
      await userFormRef.value.validate(async (valid, fields) => {
        if (valid) {
          submitLoading.value = true
          try {
            // 实际项目中应调用API
            /*
            if (isEdit.value) {
              await axios.put('/api/users/' + userForm.id, userForm)
            } else {
              await axios.post('/api/users', userForm)
            }
            */
            
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 500))
            ElMessage.success(isEdit.value ? '用户修改成功' : '用户添加成功')
            dialogVisible.value = false
            loadUserData()
          } catch (error) {
            ElMessage.error(isEdit.value ? '用户修改失败' : '用户添加失败')
            console.error('用户保存失败:', error)
          } finally {
            submitLoading.value = false
          }
        } else {
          console.error('表单验证失败:', fields)
        }
      })
    }
    
    // 确认删除用户
    const confirmDeleteUser = (user) => {
      ElMessageBox.confirm(
        `确定要删除用户 "${user.name}" 吗？此操作将不可恢复！`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteUser(user.id)
      }).catch(() => {
        // 用户取消删除操作
      })
    }
    
    // 删除用户
    const deleteUser = async (userId) => {
      loading.value = true
      try {
        // 实际项目中应调用API
        /*
        await axios.delete('/api/users/' + userId)
        */
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        ElMessage.success('用户删除成功')
        loadUserData()
      } catch (error) {
        ElMessage.error('用户删除失败')
        console.error('用户删除失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 修改用户状态
    const changeUserStatus = async (user) => {
      try {
        // 实际项目中应调用API
        /*
        await axios.patch('/api/users/' + user.id + '/status', {
          status: user.status
        })
        */
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 200))
        ElMessage.success(user.status === 1 ? '用户已启用' : '用户已禁用')
      } catch (error) {
        // 恢复状态
        user.status = user.status === 1 ? 0 : 1
        ElMessage.error('修改用户状态失败')
        console.error('修改用户状态失败:', error)
      }
    }
    
    // 处理页面大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadUserData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadUserData()
    }
    
    // 获取角色名称
    const getRoleName = (role) => {
      const roles = {
        admin: '管理员',
        user: '普通用户',
        driver: '驾驶员'
      }
      return roles[role] || role
    }
    
    // 获取角色标签类型
    const getRoleTagType = (role) => {
      const types = {
        admin: 'danger',
        user: 'primary',
        driver: 'success'
      }
      return types[role] || ''
    }
    
    return {
      userList,
      currentPage,
      pageSize,
      total,
      searchQuery,
      roleFilter,
      loading,
      submitLoading,
      currentUsername,
      dialogVisible,
      isEdit,
      userForm,
      userRules,
      userFormRef,
      debounceSearch,
      resetQuery,
      loadUserData,
      openUserDialog,
      submitUserForm,
      confirmDeleteUser,
      changeUserStatus,
      handleSizeChange,
      handleCurrentChange,
      getRoleName,
      getRoleTagType
    }
  }
}
</script> 